#!/usr/bin/python
# -*- coding: utf-8 -*-

from datetime import datetime, timedelta

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from google.appengine.ext import db

from contact.common import json
from contact.models.softinfo import SpiderTemplate
from contact.web.response import success_response, json_response

def save_template(request):
    key = request.POST.get('tpl_key', None)
    last_updated = request.POST['last_updated']
    try:
        last_updated = datetime.strptime(last_updated, '%Y-%m-%d %H:%M:%S')
    except:
        last_updated = datetime.utcnow()
    if key:
        tpl = SpiderTemplate.get(db.Key(key))
    else:
        tpl = SpiderTemplate()
    data = {
        'name': request.POST['name'],
        'start_url': request.POST['start_url'],
        'status': int(request.POST['status']),
        'last_updated': last_updated,
        'settings': request.POST['settings'],
    }
    tpl.save(data)
    return HttpResponseRedirect(reverse('list-spider-templates') + '%s/' % tpl.key())

def get_template(request):
    """获取空闲"""
    now = datetime.utcnow()
    start_date = now - timedelta(hours=8)
    for tpl in SpiderTemplate.all():
        available = False
        if tpl.status == -1:
            if tpl.last_updated is None or (tpl.last_updated - now).hours > 3: # -1 正在爬取中，且有在3个小时内未完成的
                available = True
        elif tpl.status != -1:
            if tpl.status == 0 or tpl.last_updated is None or tpl.last_updated < start_date:
                available = True
        if available:
            task = tpl.to_dict()
            tpl.status = -1
            tpl.total += 1
            tpl.save()
            return json_response(task)
    return json_response(None)

def finish_template(request, key):
    now = datetime.utcnow()
    tpl = SpiderTemplate.get(db.Key(key))
    tpl.last_updated = now
    tpl.total += 1
    tpl.success += 1
    tpl.status = 1
    tpl.save()
    return success_response()

def list_templates(request, key):
    data = {'templates': SpiderTemplate.all().fetch(1000)}
    if key is not None:
        tpl = SpiderTemplate.get(db.Key(key))
        data['select_template'] = tpl
    return render_to_response('soft/spider_tpl.html', data)